package com.starwish.starwishblog.web.front;

import com.github.pagehelper.PageInfo;
import com.mchange.lang.ShortUtils;
import com.starwish.starwishblog.entity.User;
import com.starwish.starwishblog.result.ResultResponse;
import com.starwish.starwishblog.service.UserService;
import com.starwish.starwishblog.vo.AccountVo;
import com.starwish.starwishblog.vo.HistoryVo;
import com.starwish.starwishblog.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("user")
@Api(value = "用户登录")
@Slf4j
public class FUserController {
    @Autowired
    UserService userService;
    @Value("${starwish.user}")
    String path;

    @PostMapping("/login")
    @ApiOperation(value = "用户登录操作")
    public ResultResponse<User> login(@ApiParam(name = "accountVo",value = "接受用户名和密码")
                                      @RequestBody AccountVo accountVo){
        ResultResponse<User> result = null;
        System.out.println("名称"+accountVo.getAdminName());
        User user =  userService.login(accountVo.getAdminName());
        if(user == null){
            result = new ResultResponse<>(201,"账户不存在！!");
        }else if(user.getPassword().equals(accountVo.getPassword())){
            //不为空把登录时间插入进去
            if(user.getStatus().equals("1")){
                result = new ResultResponse<>(202,"账户已冻结，请联系管理员！");
            }else {
                int i = userService.modifyLoginTime(user.getId());
                if(i>0){
                    result = new ResultResponse<>(200,"登录成功",user, null);
                }else {
                    result = new ResultResponse<>(201,"记录登录时间失败！");
                }
            }
        }else{
            result = new ResultResponse<>(202,"密码错误!");
        }
        return result;
    }
    //用户注册  添加用户
    @PostMapping("/register")
    public ResultResponse<Void> register(@RequestBody AccountVo accountVo){
        ResultResponse<Void> result = null;
        try{
            User user = new User();
            String nickName = "";
            nickName ="用户名"+UUID.randomUUID().toString().replaceAll("-", "").substring(24,30);
            user.setNickname(nickName);
            user.setUsername(accountVo.getAdminName());
            user.setPassword(accountVo.getPassword());
            user.setIsDelete("0");
            user.setStatus("0");
            user.setFanCount(0);
            user.setIsFamous("0");
            user.setFollowCount(0);
            user.setSex("男");
            user.setDescription("这个人很神秘哦~");
            user.setAvatar("01e48165a5e1461cb572006df2594171.jpg");
            user.setCreateTime(new Date());
            user.setModifyTime(new Date());
            user.setLastLogin(new Date());
          int i = userService.registerUserByKey(user);
          if(i>0){
            result = new ResultResponse<>(200,"注册成功");
          }else {
              result = new ResultResponse<>(201,"注册失败");
          }
        }catch (Exception e){
            e.printStackTrace();
            result = new ResultResponse<>(305,"注册异常");
        }
        return result;
    }
    @GetMapping("/followList")
    @ApiOperation(value = "用户关注列表")
    public ResultResponse<PageInfo<UserVo>> followList(
            @RequestParam(value = "now",defaultValue = "1") Integer now,
            @RequestParam(value = "size",defaultValue = "3") Integer size,
            String name){
        ResultResponse<PageInfo<UserVo>> result = null;
        try {
            PageInfo<UserVo> pageInfo = userService.queryByPages(now, size, name);
            result = new ResultResponse<>(200,"加载用户关注列表查询成功",pageInfo);

        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"加载用户关注列表查询失败");
        }
        return result;
    }

    @GetMapping("/FanListById")
    @ApiOperation(value = "用户粉丝列表")
    public ResultResponse<PageInfo<UserVo>> FanListById(
            @RequestParam(value = "now",defaultValue = "1") Integer now,
            @RequestParam(value = "size",defaultValue = "3") Integer size,
            @ApiParam(name = "id",value = "博主Id") @RequestParam("id") Integer id){
        ResultResponse<PageInfo<UserVo>> result = null;
        try {
            PageInfo<UserVo> pageInfo = userService.queryFansById(now,size,id);
            result = new ResultResponse<>(200,"加载粉丝列表查询成功",pageInfo);

        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"加载粉丝列表查询失败");
        }
        return result;
    }

    @GetMapping("/getFansByUserId")
    @ApiOperation(value = "用户粉丝列表")
    public ResultResponse<PageInfo<User>> getFansByUserId(
            @RequestParam(value = "now",defaultValue = "1") Integer now,
            @RequestParam(value = "size",defaultValue = "5") Integer size,
            @RequestParam("userId") Integer userId){
        ResultResponse<PageInfo<User>> result = null;
        try {
            PageInfo<User> pageInfo = userService.findFansByUserId(now,size,userId);
            result = new ResultResponse<>(200,"加载粉丝列表查询成功",pageInfo);
        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"加载粉丝列表查询失败");
        }
        return result;
    }

    @GetMapping("/getFollowsByUserId")
    @ApiOperation(value = "用户关注列表")
    public ResultResponse<PageInfo<User>> getFollowsByUserId(
            @RequestParam(value = "now",defaultValue = "1") Integer now,
            @RequestParam(value = "size",defaultValue = "5") Integer size,
            @RequestParam("userId") Integer userId){
        ResultResponse<PageInfo<User>> result = null;
        try {
            PageInfo<User> pageInfo = userService.findFollowsByUserId(now,size,userId);
            result = new ResultResponse<>(200,"加载粉丝列表查询成功",pageInfo);
        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"加载粉丝列表查询失败");
        }
        return result;
    }
    @GetMapping("/FollowListById")
    @ApiOperation(value = "用户关注列表")
    public ResultResponse<PageInfo<UserVo>> FollowListById(
            @RequestParam(value = "now",defaultValue = "1") Integer now,
            @RequestParam(value = "size",defaultValue = "3") Integer size,
            @ApiParam(name = "id",value = "用户Id") @RequestParam("id") Integer id){
        ResultResponse<PageInfo<UserVo>> result = null;
        try {
            PageInfo<UserVo> pageInfo = userService.queryFollowById(now,size,id);
            result = new ResultResponse<>(200,"加载关注列表查询成功",pageInfo);

        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"加载关注列表查询失败");
        }
        return result;
    }

    @GetMapping("/addFollow")
    public ResultResponse<Void> addFollow(@ApiParam(name = "userId",value = "用户的ID") @RequestParam(value = "userId") Integer userId,
                                          @ApiParam(name = "authorId",value = "被关注用户的ID") @RequestParam(value = "authorId") Integer authorId){
        ResultResponse<Void> result = null;
        try{
            userService.addFollowUser(userId,authorId);
            result = new ResultResponse<>(200,"添加关注成功");
        }catch (Exception e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"添加关注失败");
        }
        return result;
    }

    @GetMapping("/findFollowStatus")
    public ResultResponse<String> findFollowStatus(@ApiParam(name = "userId",value = "用户的ID") @RequestParam(value = "userId") Integer userId,
                                          @ApiParam(name = "authorId",value = "被关注用户的ID") @RequestParam(value = "authorId") Integer authorId){
        ResultResponse<String> result = null;
        try{
            String status = userService.queryFollowStatus(userId,authorId);
            result = new ResultResponse<>(200,"查询状态成功",status);
        }catch (Exception e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"查询状态失败");
        }
        return result;
    }

    @GetMapping("/cancelFollowUser")
    public ResultResponse<Void> cancelFollowUser(@ApiParam(name = "userId",value = "用户的ID") @RequestParam(value = "userId") Integer userId,
                                                 @ApiParam(name = "authorId",value = "被关注用户的ID") @RequestParam(value = "authorId") Integer authorId){
        ResultResponse<Void> result = null;
        try{
            int i = userService.cancelFollowUserByKey(userId, authorId);
            if(i>0){
            result = new ResultResponse<>(200,"取消关注成功");
            }else {
                result = new ResultResponse<>(201,"取消关注失败");

            }
        }catch (Exception e){
            e.printStackTrace();
            result = new ResultResponse<>(305,"取消关注异常");
        }
        return result;
    }

    //用户修改
    @PutMapping("/modify")
    @ApiOperation(value = "用户修改")
    public ResultResponse<Void> modify(@RequestBody User user) {
        ResultResponse<Void> result = null;
        try {
            user.setModifyTime(new Date());
            int i = userService.modifyUserByKey(user);
            if (i > 0) {
                result = new ResultResponse<>(200, "更新成功");
            } else {
                result = new ResultResponse<>(201, "更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResultResponse<>(200, "更新权限异常");
        }
        return result;
    }
    //用户删除
    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "注销用户")
    public ResultResponse<Void> del(@ApiParam(name = "id",value = "用户的ID") @PathVariable("id") Integer id){
        ResultResponse<Void> result = null;
        try{
            int i = userService.deleteUserByKey(id);
            if(i == 1){
                result = new ResultResponse<>(200, "删除用户成功！");
            }else {
                result = new ResultResponse<>(201, "删除用户失败！");
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            result = new ResultResponse<>(305, "删除用户异常");
        }
        return result;
    }
    //更具Id查询他人信息
    @GetMapping("/findUserByKey/{id}")
    public ResultResponse<User> findUserByKey(@ApiParam(name = "id",value = "查询用户用的Id") @PathVariable("id") Integer id){
        ResultResponse<User> result = null;
        try{
            User user = userService.queryUserByKey(id);
            if(user ==null){
                result = new ResultResponse<>(201, "查询用户失败！");
            }else {
                result = new ResultResponse<>(200, "查询用户成功！",user);
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(305, "查询用户异常！");

        }
            return result;
    }

    @GetMapping("/changeLocked")
    public ResultResponse<Void> changeLocked(@RequestParam("id")Integer id,@RequestParam("status") Integer status){
        ResultResponse<Void> result = null;
        try {
            int i = userService.updateLocked(id,status);
            if(i > 0){
                result = new ResultResponse<>(200,"修改成功");
            }else{
                result = new ResultResponse<>(201,"修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResultResponse<>(305,"系统错误");
        }
        return result;
    }

    @GetMapping("/hList")
    @ApiOperation(value = "后台查看历史记录")
    public ResultResponse<PageInfo<HistoryVo>> hList(
            @RequestParam(value = "now",defaultValue = "1") Integer now,
            @RequestParam(value = "size",defaultValue = "10") Integer size,
            String username){
        ResultResponse<PageInfo<HistoryVo>> result = null;
        try {
            PageInfo<HistoryVo> pageInfo = userService.queryUserHistoryByPages(now, size, username);
            result = new ResultResponse<>(200,"加载浏览历史列表查询成功",pageInfo);

        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"加载浏览历史数列表查询失败");
        }
        return result;
    }

    @GetMapping("/getViewHistory")
    public ResultResponse<PageInfo<HistoryVo>> getViewHistory(
            @RequestParam(value = "now",defaultValue = "1") Integer now,
            @RequestParam(value = "size",defaultValue = "10") Integer size,
            @RequestParam(value = "userId")Integer userId){
        ResultResponse<PageInfo<HistoryVo>> result = null;
        try {
            PageInfo<HistoryVo> pageInfo = userService.findUserHistoryByUserId(now, size,userId);
            result = new ResultResponse<>(200,"加载浏览历史列表查询成功",pageInfo);
        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"加载浏览历史数列表查询失败");
        }
        return result;
    }

    @PostMapping("/addHistory")
    @ApiOperation("添加历史记录")
    public ResultResponse<Void> addHistory(@ApiParam(name = "userId",value = "用户的ID") @RequestParam(value = "userId") Integer userId,
                                          @ApiParam(name = "articleId",value = "文章ID") @RequestParam(value = "articleId") Integer articleId){
        ResultResponse<Void> result = null;
        try{
            HistoryVo historyVo = new HistoryVo();
            historyVo.setUserId(userId);
            historyVo.setArticleId(articleId);
            historyVo.setCreateTime(new Date());
           int i = userService.insertHistoryById(historyVo);
            result = new ResultResponse<>(200,"添加历史记录成功");
        }catch (Exception e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"添加历史记录失败");
        }
        return result;
    }

    @DeleteMapping("/delHistory/{id}")
    @ApiOperation(value = "删除单条的历史记录")
    public ResultResponse<Void> delHistory(@ApiParam(name = "id",value = "历史记录的ID") @PathVariable("id") Integer id){
        ResultResponse<Void> result = null;
        try{
            int i = userService.deleteUserHistoryByKey(id);
            if(i == 1){
                result = new ResultResponse<>(200, "删除历史记录成功！");
            }else {
                result = new ResultResponse<>(201, "删除历史记录失败！");
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            result = new ResultResponse<>(305, "删除历史记录异常");
        }
        return result;
    }
    @DeleteMapping("/delHistoryByUserId/{id}")
    @ApiOperation(value = "删除单条的历史记录")
    public ResultResponse<Void> delHistoryByUserId(@ApiParam(name = "id",value = "用户的ID") @PathVariable("id") Integer id){
        ResultResponse<Void> result = null;
        try{
            int i = userService.deleteUserHistoryByUserId(id);
            if(i>0){
                result = new ResultResponse<>(200, "删除用户的历史记录成功！");
            }else {
                result = new ResultResponse<>(201, "删除用户的历史记录失败！");
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            result = new ResultResponse<>(201, "删除用户的历史记录异常");
        }
        return result;
    }

    @PutMapping("/recoverUserHistory")
    @ApiOperation(value = "恢复用户浏览历史记录")
    public ResultResponse<Void> recoverUserHistory(@ApiParam(name = "userId",value = "用户Id") @RequestParam("userId") Integer userId) {
        ResultResponse<Void> result = null;
        try {
            int i = userService.recoverUserHistoryByKey(userId);
            if (i > 0) {
                result = new ResultResponse<>(200, "恢复成功");
            } else {
                result = new ResultResponse<>(201, "恢复失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResultResponse<>(305, "系统异常");
        }
        return result;
    }
    @GetMapping("/loginOut")
    @ApiOperation("用户退出方法")
    public ResultResponse<Void>  loginOut(){
        ResultResponse<Void> result = null;
        try {
            result = new ResultResponse<>(200,"退出登录");
        }catch (Exception e){
            e.printStackTrace();
            result = new ResultResponse<>(205,"系统错误");
        }
        return result;
    }
    //重名认证
    @GetMapping("/checkRepeatName")
    public ResultResponse<Void> checkRepeatName(@RequestParam("username") String username){
        ResultResponse<Void> result = null;
         User user =  userService.login(username);
        if(user == null){
            result = new ResultResponse<>(200,"账户不存在！,可以使用");
        }else {
            result = new ResultResponse<>(201,"账户存在！,不能可以使用");
        }
        return result;
    }
    @PostMapping("/upload")
    public ResultResponse<String> upload(@RequestParam(value = "userImg") MultipartFile multipartFile){
        ResultResponse<String> result = null;
        try {
            String filename = multipartFile.getOriginalFilename();
            log.info("上传的原名字"+filename);
            filename = UUID.randomUUID().toString().replace("-", "")+filename.substring(filename.lastIndexOf("."));
            log.info("上传后的文件名"+filename);
            File file = new File(path);
            if(!file.exists()){
                file.mkdir();
            }
            File f = new File(file,filename);
            multipartFile.transferTo(f);
            result = new ResultResponse<>(200,"上传成功!",filename);
        }catch (IOException e){
            e.printStackTrace();
            result = new ResultResponse<>(202,"上传异常!");
        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(202,"上传异常!");
        }
        return result;
    }

}
